package org.stvd.core.web.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.stvd.core.web.URLUtil;

/**
 * 
 * 设置字符编码并对相关信息进行转码
 *
 */
public class SysCharacterEncodingFilter extends CharacterEncodingFilter {

    private final PathMatcher pathMatcher = new AntPathMatcher();
    private Set<String> excludesPattern;
    protected String contextPath;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        /*
         * forceTranscode ： 是否强制对输入信息进行转码，是：true，默认全路径信息转码
         * exclusionsTranscodePath：如果forceTranscode=true，该参数有效。该参数配置不需要转码的路径
         */
        String forceTranscode = this.getFilterConfig().getInitParameter("forceTranscode");
        if (!StringUtils.isEmpty(forceTranscode) && "true".equals(forceTranscode)) {
            String exclusions = this.getFilterConfig().getInitParameter("exclusionsTranscodePath");
            if (!StringUtils.isEmpty(exclusions)) {
                excludesPattern = new HashSet<String>(Arrays.asList(exclusions.split("\\s*,\\s*")));
                contextPath = URLUtil.getContextPath(this.getFilterConfig().getServletContext());
                if (isExclusion(request.getRequestURI())) {
                    super.doFilterInternal(request, response, filterChain);
                    return;
                }
            }
            super.doFilterInternal(new CharacterTranscodeRequest(request, request.getParameterMap()), response,
                    filterChain);
        } else {
            super.doFilterInternal(request, response, filterChain);
        }
    }

    private boolean isExclusion(String requestURI) {
        String requestUri = requestURI;
        if (excludesPattern == null || requestUri == null) {
            return false;
        }

        if (contextPath != null && requestUri.startsWith(contextPath)) {
            requestUri = requestUri.substring(contextPath.length());
            if (!requestUri.startsWith("/")) {
                requestUri = "/" + requestUri;
            }
        }

        for (String pattern : excludesPattern) {
            if (pathMatcher.match(pattern, requestUri)) {
                return true;
            }
        }

        return false;
    }
}
